package com.ruoyi.project.zerocarbon.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.QiniuUtils;
import com.ruoyi.common.utils.file.ZipFileUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.zerocarbon.auth.APIValidateUtil;
import com.ruoyi.project.zerocarbon.auth.AccountLoginDTO;
import com.ruoyi.project.zerocarbon.domain.Declaration;
import com.ruoyi.project.zerocarbon.domain.DeclareAuthor;
import com.ruoyi.project.zerocarbon.domain.DeclareFile;
import com.ruoyi.project.zerocarbon.domain.dto.DeclarationDTO;
import com.ruoyi.project.zerocarbon.mapper.DeclarationMapper;
import com.ruoyi.project.zerocarbon.mapper.DeclareAuthorMapper;
import com.ruoyi.project.zerocarbon.mapper.DeclareFileMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.file.FileUtils.percentEncode;
import static com.ruoyi.common.utils.file.QiniuUtils.getQiniuPath;

/**
 * @类名: DeclarationController
 * @描述:
 * @作者:
 * @日期: 2021/6/26 15:07
 */
@Slf4j
@Api("申报")
@RequestMapping("/declaration")
@RestController
public class DeclarationController extends BaseController {

    @Autowired
    private DeclarationMapper declarationMapper;
    @Autowired
    private DeclareAuthorMapper declareAuthorMapper;
    @Autowired
    private DeclareFileMapper declareFileMapper;
    @Autowired
    private APIValidateUtil apiValidateUtil;
    @Resource
    private QiniuUtils qiniuUtils;
    @Value("${ruoyi.profile}")
    private String defaultFilePath;
    @Value("${declaration.auth.accessKeyId}")
    private String accessKeyId;
    @Value("${declaration.auth.accessKeySecret}")
    private String accessKeySecret;
    @Value("${declaration.auth.zyzUrl}")
    private String zyzUrl;
    @Value("${declaration.auth.tokenUrl}")
    private String tokenUrl;
    @Value("${declaration.auth.loginUrl}")
    private String loginUrl;
    @Value("${declaration.auth.logoutUrl}")
    private String logoutUrl;
    @Value("${declaration.auth.sendCodeUrl}")
    private String sendCodeUrl;
    @Value("${declaration.auth.checkCodeUrl}")
    private String checkCodeUrl;
    @Value("${declaration.auth.areaUrl}")
    private String areaUrl;
    @Value("${declaration.auth.registerUrl}")
    private String registerUrl;

    /**
     * 登录
     * @param dto
     * @return
     */
    @ApiOperation("美丽中国登录")
    @GetMapping("/login")
    public AjaxResult login(AccountLoginDTO dto) {
        //每个用户只能提交一次
        Assert.notNull(dto.getAccount());
        Assert.notNull(dto.getPassword());
        Map<String,String> mapv=new HashMap<String, String>();
        mapv.put("AccessKeyId", accessKeyId);
        mapv.put("username", dto.getAccount());
        mapv.put("password", dto.getPassword());
        try {
            String key = apiValidateUtil.computeSignature(mapv, accessKeySecret);
            String rspStr = "username="+dto.getAccount()+"&password="+dto.getPassword()+"&AccessKeyId="+mapv.get("AccessKeyId")+"&Signature="+percentEncode(key);
            String response = HttpUtils.sendPost(loginUrl, rspStr);
            return AjaxResult.success(JSONObject.parseObject(response));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success("登录失败");
    }

    @ApiOperation("发送短信验证码")
    @GetMapping("/sendCode")
    public AjaxResult getCode(String phone) {
        Assert.notNull(phone);
        Map<String,String> mapv=new HashMap<String, String>();
        mapv.put("AccessKeyId", accessKeyId);
        mapv.put("type", "1");
        mapv.put("tel", phone);
        String response = null;
        try {
            String key = apiValidateUtil.computeSignature(mapv, accessKeySecret);
            String rspStr = "type="+"1"+"&tel="+phone+"&AccessKeyId="+mapv.get("AccessKeyId")+"&Signature="+percentEncode(key);
            response = HttpUtils.sendPost(sendCodeUrl, rspStr);
            log.info("发送短信验证码 response: {}",response);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("发送短信验证码失败:"+response);
        }
    }

//    @ApiOperation("校验短信验证码")
//    @GetMapping("/checkCode")
//    public AjaxResult checkCode(String phone,String code) {
//        Assert.notNull(phone);
//        Map<String,String> mapv=new HashMap<String, String>();
//        mapv.put("AccessKeyId", accessKeyId);
//        mapv.put("type", "1");
//        mapv.put("tel", phone);
//        mapv.put("code", code);
//        String response = null;
//        try {
//            String key = apiValidateUtil.computeSignature(mapv, accessKeySecret);
//            String rspStr = "type="+"1"+"&tel="+phone+"&code="+code+"&AccessKeyId="+mapv.get("AccessKeyId")+"&Signature="+percentEncode(key);
//            response = HttpUtils.sendPost(checkCodeUrl, rspStr);
//            JSONObject jsonObject = JSONObject.parseObject(response);
//            if (jsonObject.get("status") != null && jsonObject.get("status").toString().equals("true")){
//                return AjaxResult.success();
//            }else {
//                return AjaxResult.error(jsonObject.get("message").toString());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.error(response);
//        }
//    }

    @ApiOperation("获取省市区联动")
    @GetMapping("/getArea")
    public AjaxResult getArea(String parentid) {
        Assert.notNull(parentid);
        Map<String,String> mapv=new HashMap<String, String>();
        mapv.put("AccessKeyId", accessKeyId);
        mapv.put("typecode", "areatree");
        mapv.put("parentid", parentid);
        String response = null;
        try {
            String key = apiValidateUtil.computeSignature(mapv, accessKeySecret);
            String rspStr = "typecode="+"areatree"+"&parentid="+parentid+"&AccessKeyId="+mapv.get("AccessKeyId")+"&Signature="+percentEncode(key);
            response = HttpUtils.sendPost(areaUrl, rspStr);
            if (response.startsWith("[")){
                JSONArray array = JSONArray.parseArray(response);
                return AjaxResult.success(array);
            }
            return AjaxResult.success(JSONObject.parseObject(response));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(response);
        }
    }

    @ApiOperation("注册志愿者中国")
    @GetMapping("/register")
    public AjaxResult register(String phone,String password,String name,String idcardType,String idcard,String regprovince,String regcity,String regcounty,String code) {
        Assert.notNull(phone);
        Assert.notNull(password);
        Assert.notNull(name);
        Assert.notNull(idcard);
        Assert.notNull(code);
        String codeResponse = checkPhoneCode(phone, code);
        JSONObject jsonObject = JSONObject.parseObject(codeResponse);
        if (jsonObject.get("status") != null && jsonObject.get("status").toString().equals("true")){

        }else {
            return AjaxResult.success(jsonObject);
        }
        Map<String,String> mapv=new HashMap<String, String>();
        mapv.put("AccessKeyId", accessKeyId);
        mapv.put("mphone", phone);
        mapv.put("password", password);
        mapv.put("name", name);
        mapv.put("idcardtype", StringUtils.isEmpty(idcardType)?"1":idcardType);
        mapv.put("idcard", idcard);
        mapv.put("regprovince", regprovince);
        mapv.put("regcity", regcity);
        mapv.put("regcounty", regcounty);
        String response = null;
        try {
            String key = apiValidateUtil.computeSignature(mapv, accessKeySecret);
            String rspStr = "&mphone="+phone+"&password="+password+"&name="+name+"&idcardtype="+mapv.get("idcardtype")+"&idcard="+idcard+"&regprovince="+regprovince+"&regcity="+regcity+"&regcounty="+regcounty+"&AccessKeyId="+mapv.get("AccessKeyId")+"&Signature="+percentEncode(key);
            response = HttpUtils.sendPost(registerUrl, rspStr);
            if (response.startsWith("[")){
                JSONArray array = JSONArray.parseArray(response);
                return AjaxResult.success(array);
            }
            return AjaxResult.success(JSONObject.parseObject(response));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(response);
        }
    }

    private String checkPhoneCode(String phone,String code) {
        Assert.notNull(phone);
        Map<String,String> mapv=new HashMap<String, String>();
        mapv.put("AccessKeyId", accessKeyId);
        mapv.put("type", "1");
        mapv.put("tel", phone);
        mapv.put("code", code);
        String response = null;
        try {
            String key = apiValidateUtil.computeSignature(mapv, accessKeySecret);
            String rspStr = "type="+"1"+"&tel="+phone+"&code="+code+"&AccessKeyId="+mapv.get("AccessKeyId")+"&Signature="+percentEncode(key);
            response = HttpUtils.sendPost(checkCodeUrl, rspStr);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

//    /api/comm/sendMessage.do

    /**
     * 退出登录
     * @param token
     * @return
     */
    @ApiOperation("美丽中国退出登录")
    @GetMapping("/logout")
    public AjaxResult logout(String token) {
        //每个用户只能提交一次
        Assert.notNull(token);
        if (StringUtils.isEmpty(token)){
            return AjaxResult.error("token不能为空");
        }
        Map<String,String> mapv=new HashMap<String, String>();
        mapv.put("AccessKeyId", accessKeyId);
        try {
            String key = apiValidateUtil.computeSignature(mapv, accessKeySecret);
            String rspStr = "&AccessKeyId="+mapv.get("AccessKeyId")+"&Signature="+percentEncode(key);
            String response = HttpUtils.sendPost(logoutUrl, rspStr, token);
            return AjaxResult.success(JSONObject.parseObject(response));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("退出登录失败");
    }

    @GetMapping("/signature/get")
    public AjaxResult getSignature(String zyzid)
    {
        Map<String,String> mapv=new HashMap<String, String>();
        mapv.put("AccessKeyId", accessKeyId);
        if (StringUtils.isNotEmpty(zyzid)){
            mapv.put("zyzid", zyzid);
        }
        String key= null;
        try {
            String s = apiValidateUtil.computeSignature(mapv, accessKeySecret);
            key = percentEncode(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("getSignature: zyzid {},key {}",zyzid,key);
        return AjaxResult.success("操作成功",key);
    }

    /**
     * 根据token获取志愿者id
     * @param token
     * @return
     */
    @ApiOperation("根据token获取志愿者id")
    @GetMapping("/zyz/getZyzidByToken")
    public AjaxResult getZyzidByToken(String token)
    {
        if (StringUtils.isEmpty(token)){
            return AjaxResult.error("token不能为空");
        }
        Map<String,String> mapv=new HashMap<String, String>();
        mapv.put("AccessKeyId", accessKeyId);
        try {
            String key = apiValidateUtil.computeSignature(mapv, accessKeySecret);
            String rspStr = "&AccessKeyId="+mapv.get("AccessKeyId")+"&Signature="+percentEncode(key);
            String response = HttpUtils.sendPost(tokenUrl, rspStr, token);
            return AjaxResult.success(JSONObject.parseObject(response));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("获取志愿者id失败");
    }

    @ApiOperation("根据志愿者id获取用户信息")
    @GetMapping("/zyz/getUserByZyzid")
    public AjaxResult getUserByZyzid(String zyzid)
    {
        if (StringUtils.isEmpty(zyzid)){
            return AjaxResult.error("zyzid不能为空");
        }
        Map<String,String> mapv=new HashMap<String, String>();
        mapv.put("AccessKeyId", accessKeyId);
        if (StringUtils.isNotEmpty(zyzid)){
            mapv.put("zyzid", zyzid);
        }
        try {
            String key = apiValidateUtil.computeSignature(mapv, accessKeySecret);
            String rspStr = "zyzid="+mapv.get("zyzid")+"&AccessKeyId="+mapv.get("AccessKeyId")+"&Signature="+percentEncode(key);
            String response = HttpUtils.sendGet(zyzUrl, rspStr);

            return AjaxResult.success(JSONObject.parseObject(response));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("获取用户信息失败");
    }

    /**
     * 注册
     * @param dto
     * @return
     */
    @ApiOperation("app预约申报")
    @PostMapping("/subscribe")
    public AjaxResult subscribe(@Validated @RequestBody DeclarationDTO dto) {
        //每个用户只能提交一次
        Assert.notNull(dto.getAccount());
        Declaration declaration = new Declaration();
        declaration.setAccount(dto.getAccount());
        Declaration declarationHistory = declarationMapper.selectByAccountAndType(dto.getAccount(),dto.getManagementType());
        if (declarationHistory != null){
            return AjaxResult.success(declarationHistory);
        }
        declaration.setSaveType(dto.getSaveType());
        declarationMapper.insertDeclaration(declaration);
        return AjaxResult.success(declaration);
    }

    /**
     * 保存或提交申报
     * @param dto
     * @return
     */
    @ApiOperation("保存草稿或提交申报")
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody DeclarationDTO dto) {
        //每个用户只能提交一次
        Assert.notNull(dto.getAccount());
        Assert.notNull(dto.getManagementType());
        //判断要求35周岁以下的人占到团队的2/3
        checkAuthor(dto.getDeclareAuthors());
        Declaration declaration = new Declaration();
        declaration.setAccount(dto.getAccount());
        Declaration declarationHistory = declarationMapper.selectByAccountAndType(dto.getAccount(),dto.getManagementType());
        if (declarationHistory != null){
            if (declarationHistory.getSaveType() != null && declarationHistory.getSaveType() ==1){
                return AjaxResult.error("申报已经提交，不可修改");
            }
            declarationMapper.deleteDeclarationById(declarationHistory.getId());
            declareAuthorMapper.removeByDeclarationId(declarationHistory.getId());
            declareFileMapper.removeByDeclarationId(declarationHistory.getId());
        }
        BeanUtils.copyProperties(dto,declaration);
        //序列号,查询已有managementType类型数据,保存类型不生成序列号
        if (dto.getSaveType() != null && dto.getSaveType() != 0){
            Integer countByManagementType = declarationMapper.countByManagementType(dto.getManagementType());
            if (countByManagementType == null || countByManagementType<=0){
                declaration.setRegionSerial("000001");
            }else {
                declaration.setRegionSerial(NumberUtils.buildSerial(countByManagementType));
            }
        }
        //作者人数
        if (!CollectionUtils.isEmpty(dto.getDeclareAuthors())){
            declaration.setAuthorNumber(dto.getDeclareAuthors().size());
        }
        int saveSuccess = declarationMapper.insertDeclaration(declaration);
        if (saveSuccess > 0){
            Long declarationId = declaration.getId();
            if (!CollectionUtils.isEmpty(dto.getDeclareAuthors())){
                for (int i = 0; i < dto.getDeclareAuthors().size(); i++) {
                    DeclareAuthor declareAuthor = dto.getDeclareAuthors().get(i);
                    declareAuthor.setDeclarationId(declarationId);
                    declareAuthorMapper.insert(declareAuthor);
                }
            }
            if (!CollectionUtils.isEmpty(dto.getDeclareFiles())){
                for (int i = 0; i < dto.getDeclareFiles().size(); i++) {
                    DeclareFile declareFile = dto.getDeclareFiles().get(i);
                    declareFile.setDeclarationId(declarationId);
                    declareFileMapper.insert(declareFile);
                }
            }
        }
        if (declaration.getSaveType() != null && declaration.getSaveType() ==1){
            List<DeclareFile> declareFiles = declareFileMapper.selectByDeclarationId(declaration.getId());
            if (!CollectionUtils.isEmpty(declareFiles)){
                //                打包zip
                String zipPath = "declaration/zip/"+declaration.getHead().trim() + "-" + declaration.getId() + ".zip";
                List<String> collect = declareFiles.stream().map(DeclareFile::getQiniuPath).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect)){
                    log.info("打包zip QiniuPath: {},getQiniuPath is null",declaration.getQiniuzippath());
                    return AjaxResult.success();
                }
                String zipid = qiniuUtils.zipFiles(collect,zipPath);
                declaration.setQiniuzipid(zipid);
                declaration.setQiniuzippath(getQiniuPath(zipPath));
                log.info("打包zip QiniuPath: {},zipid:{}",declaration.getQiniuzippath(),zipid);
                declarationMapper.updateDeclaration(declaration);
            }
        }
        return AjaxResult.success(declaration);
    }

    private void checkAuthor(List<DeclareAuthor> declareAuthors){
        if (!CollectionUtils.isEmpty(declareAuthors)){
            int overAge = 0;
            int count = declareAuthors.size();
            for (int i = 0; i < declareAuthors.size(); i++) {
                if (declareAuthors.get(i).getAge() != null && declareAuthors.get(i).getAge() > 35){
                    overAge += 1;
                }
            }
            double result = new BigDecimal((float)overAge / count).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            if (result > 0.33){
                throw new CustomException("35周岁以下的人需占到团队的2/3");
            }
        }
    }
/*
    public static void main(String[] args) {
        int overAge = 1;
        int count = 3;

        double result = new BigDecimal((float)overAge / count).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        if (result > 0.33){
            throw new CustomException("35周岁以下的人需占到团队的2/3");
        }
    }*/

    /**
     * 编辑申报草稿
     * @param dto
     * @return
     */
    @ApiOperation("编辑申报")
    @PostMapping("/update")
    public AjaxResult update(@Validated @RequestBody DeclarationDTO dto) {
        //每个用户只能提交一次
        //判断要求35周岁以下的人占到团队的2/3
        checkAuthor(dto.getDeclareAuthors());
        Declaration declarationHistory = declarationMapper.selectDeclarationById(dto.getId());
        if (declarationHistory != null){
            if (declarationHistory.getSaveType() != null && declarationHistory.getSaveType() ==1){
                return AjaxResult.success("申报已经提交，不可修改");
            }
            String regionSerial = null;
            if (dto.getSaveType() != null && dto.getSaveType() != 0 && StringUtils.isEmpty(declarationHistory.getRegionSerial())){
                Integer countByManagementType = declarationMapper.countByManagementType(dto.getManagementType());
                if (countByManagementType == null || countByManagementType<=0){
                    regionSerial = "000001";
                }else {
                    regionSerial = NumberUtils.buildSerial(countByManagementType);
                }
            }
            BeanUtils.copyProperties(dto,declarationHistory);
            if (StringUtils.isNotEmpty(regionSerial)){
                declarationHistory.setRegionSerial(regionSerial);
            }
            declareAuthorMapper.removeByDeclarationId(declarationHistory.getId());
            declareFileMapper.removeByDeclarationId(declarationHistory.getId());
            declarationMapper.updateDeclaration(declarationHistory);
            if (!CollectionUtils.isEmpty(dto.getDeclareAuthors())){
                Long declarationId = declarationHistory.getId();
                for (int i = 0; i < dto.getDeclareAuthors().size(); i++) {
                    DeclareAuthor declareAuthor = dto.getDeclareAuthors().get(i);
                    declareAuthor.setDeclarationId(declarationId);
                    declareAuthorMapper.insert(declareAuthor);
                }
            }
            if (!CollectionUtils.isEmpty(dto.getDeclareFiles())){
                for (int i = 0; i < dto.getDeclareFiles().size(); i++) {
                    DeclareFile declareFile = dto.getDeclareFiles().get(i);
                    declareFile.setDeclarationId(declarationHistory.getId());
                    declareFileMapper.insert(declareFile);
                }
            }
            if (declarationHistory.getSaveType() != null && declarationHistory.getSaveType() ==1){
                List<DeclareFile> declareFiles = declareFileMapper.selectByDeclarationId(declarationHistory.getId());
                if (!CollectionUtils.isEmpty(declareFiles)){
                    //                打包zip
                    String zipPath = "declaration/zip/"+declarationHistory.getHead().trim() + "-" + declarationHistory.getId() + ".zip";
                    List<String> collect = declareFiles.stream().map(DeclareFile::getQiniuPath).collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(collect)){
                        log.info("打包zip QiniuPath: {},getQiniuPath is null",declarationHistory.getQiniuzippath());
                        return AjaxResult.success();
                    }
                    String zipid = qiniuUtils.zipFiles(collect,zipPath);
                    declarationHistory.setQiniuzipid(zipid);
                    declarationHistory.setQiniuzippath(getQiniuPath(zipPath));
                    log.info("打包zip QiniuPath: {},zipid:{}",declarationHistory.getQiniuzippath(),zipid);
                    declarationMapper.updateDeclaration(declarationHistory);
                }
            }
            return AjaxResult.success(declarationHistory);
        }
        Declaration declaration = new Declaration();
        BeanUtils.copyProperties(dto,declaration);
        if (dto.getSaveType() != null && dto.getSaveType() != 0){
            Integer countByManagementType = declarationMapper.countByManagementType(dto.getManagementType());
            if (countByManagementType == null || countByManagementType<=0){
                declaration.setRegionSerial("000001");
            }else {
                declaration.setRegionSerial(NumberUtils.buildSerial(countByManagementType));
            }
        }
        int saveSuccess = declarationMapper.insertDeclaration(declaration);
        if (saveSuccess > 0){
            Long declarationId = declaration.getId();
            if (!CollectionUtils.isEmpty(dto.getDeclareAuthors())){
                for (int i = 0; i < dto.getDeclareAuthors().size(); i++) {
                    DeclareAuthor declareAuthor = dto.getDeclareAuthors().get(i);
                    declareAuthor.setDeclarationId(declarationId);
                    declareAuthorMapper.insert(declareAuthor);
                }
            }
            if (!CollectionUtils.isEmpty(dto.getDeclareFiles())){
                for (int i = 0; i < dto.getDeclareFiles().size(); i++) {
                    DeclareFile declareFile = dto.getDeclareFiles().get(i);
                    declareFile.setDeclarationId(declarationId);
                    declareFileMapper.insert(declareFile);
                }
            }
        }
        if (declaration.getSaveType() != null && declaration.getSaveType() ==1){
            List<DeclareFile> declareFiles = declareFileMapper.selectByDeclarationId(declaration.getId());
            if (!CollectionUtils.isEmpty(declareFiles)){
                //                打包zip
                String zipPath = "declaration/zip/"+declaration.getHead().trim() + "-" + declaration.getId() + ".zip";
                List<String> collect = declareFiles.stream().map(DeclareFile::getQiniuPath).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect)){
                    log.info("打包zip QiniuPath: {},getQiniuPath is null",declaration.getQiniuzippath());
                    return AjaxResult.success();
                }
                String zipid = qiniuUtils.zipFiles(collect,zipPath);
                declaration.setQiniuzipid(zipid);
                declaration.setQiniuzippath(getQiniuPath(zipPath));
                log.info("打包zip QiniuPath: {},zipid:{}",declaration.getQiniuzippath(),zipid);
                declarationMapper.updateDeclaration(declaration);
            }
        }
        return AjaxResult.success(declaration);
    }

    /**
     * 查看申报
     * @param account
     * @return
     */
    @ApiOperation("查看申报详情")
    @GetMapping("/detail")
    public AjaxResult detail(String account,Integer managementType) {
        Assert.notNull(account);
        Assert.notNull(managementType);
        Declaration declarationHistory = declarationMapper.selectByAccountAndType(account,managementType);
        DeclarationDTO declarationDTO = new DeclarationDTO();
        if (declarationHistory != null && declarationHistory.getManagementType() != null && declarationHistory.getManagementType() == managementType){
            BeanUtils.copyProperties(declarationHistory,declarationDTO);
            List<DeclareAuthor> collection = declareAuthorMapper.selectByDeclarationId(declarationHistory.getId());
            declarationDTO.setDeclareAuthors(collection);
            declarationDTO.setDeclareFiles(declareFileMapper.selectByDeclarationId(declarationHistory.getId()));
            return AjaxResult.success(declarationDTO);
        }
        return AjaxResult.success();
    }

    @ApiOperation("申报文件上传")
    @PostMapping("/attach/upload")
    public AjaxResult upload(@RequestParam(value = "file") MultipartFile file) {
        if (file != null){
            File dest = new File(defaultFilePath + System.currentTimeMillis() + "-" + file.getOriginalFilename());
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return AjaxResult.success("操作成功",dest.getAbsolutePath());
        }
        return AjaxResult.success();
    }

    @ApiOperation("申报文件删除")
    @GetMapping("/attach/delete")
    public AjaxResult removeRobot(String filePath) {
        Assert.notNull(filePath);
        if (new File(filePath).exists()){
            new File(filePath).delete();
        }
        return AjaxResult.success();
    }

    @ApiOperation("申报文件打包下载:declarationIdList")
    @GetMapping("/attach/download")
    public void fileDownload(Long declarationId, HttpServletResponse response, HttpServletRequest request)
    {
//        for (Long declarationId:declarationIdList){
            try
            {
                Declaration declaration = declarationMapper.selectDeclarationById(declarationId);
                String zipFilePath = "/home/declaration/file/"+declaration.getHead().trim()+"-"+declaration.getId()+".zip";
                if (!new File(zipFilePath).exists()){
                    List<DeclareFile> declareFiles = declareFileMapper.selectByDeclarationId(declarationId);
                    if (!CollectionUtils.isEmpty(declareFiles)){
                        ZipFileUtils.toZip(declareFiles.stream().map(DeclareFile::getPath).collect(Collectors.toList()),new FileOutputStream(new File(zipFilePath)));
                    }else {
                        log.info("该用户无文件");
                        return;
                    }
                }
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                FileUtils.setAttachmentResponseHeader(response, zipFilePath.substring(zipFilePath.lastIndexOf("/")+1));
                FileUtils.writeBytes(zipFilePath, response.getOutputStream());
            }
            catch (Exception e)
            {
                log.error("下载文件失败", e);
            }
//        }
    }

}
